const fs = require('fs');

/**
 * 通用类
 * @version 1.0.0
 */
class EsUtils {
    /**
     * 获取标准格式的消息数据
     */
    stdMessage(success, message, data = null, code = 200) {
        return { success, message, data, code };
    }
    /**
     * 获取标准格式的路径数据
     */
    stdPath(pathStr, trimStart = false, paddingEnd = false) {
        if (trimStart && pathStr.startsWith('/')) {
            pathStr = pathStr.substring(1);
        }
        if (paddingEnd && !pathStr.endsWith('/')) {
            pathStr += '/';
        }
        return pathStr.replace(/[\/]+/g, '/');
    }
    /**
     * 获取标准格式的数组分页数据
     */
    stdPagingData(list, pageId = 1, pageSize = 20, total = 0, isPaging = true) {
        let items = []
        if (isPaging) {
            let start = (pageId - 1) * pageSize;
            let end = start + pageSize;
            items = list.slice(start, end);
        } else {
            items = list;
        }
        total = total == 0 ? list.length : total;
        let pageCount = total > 0 ? Math.ceil(total / pageSize) : 0;
        return {
            total,
            per_page: pageSize,
            current_page: pageId,
            last_page: pageCount,
            data: items,
        }
    }
    /**
     * 修改文件后缀名
     */
    changeExt(pathStr, fromExt, toExt) {
        if (!pathStr) {
            return '';
        }
        return pathStr.slice(0, -fromExt.length) + toExt;
    }
    /**
     * 字节单位转换
     */
    bytesToSize(bytes) {
        if (bytes === 0) {
            return '0 B';
        }
        var k = 1024, // or 1024
            sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(bytes) / Math.log(k));

        return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
    }
    basename(pathStr) {
        if (pathStr.endsWith('/')) {
            pathStr = pathStr.slice(0, -1);
        }
        let idx = pathStr.lastIndexOf('/');
        return idx > -1 ? pathStr.substring(idx + 1) : pathStr;
    }
    mkdir(pathStr) {
        if (!fs.existsSync(pathStr)) {
            fs.mkdirSync(pathStr, { recursive: true });
        }
    }
    /**
     * 剪短文字
     */
    truncateText(text, length, ellipsis = '') {
        if (!text || text.length < length) {
            return text;
        }
        return text.substring(0, length) + ellipsis;
    }
    
}

module.exports = EsUtils;